using System;
using System.Web;
using Tools.Common.UnitOfWork.Contracts;

namespace Web.App.Infrastructure.UnitOfWork.Implementations
{
    public class UoWWebContainer : IUoWContainer 
    {
        private const string UNIT_OF_WORK = "Application.UnitOfWork.Current";
        private const string LONG_CONVERSATION_KEY = "LongConversationKey";

        public IUnitOfWork Current
        {
            get
            {
                if(UnitOfWork.Current == null)
                {
                    Guid? uowKey = null;
                    if (!string.IsNullOrEmpty(HttpContext.Current.Request[LONG_CONVERSATION_KEY]))
                        uowKey = new Guid(HttpContext.Current.Request[LONG_CONVERSATION_KEY]);
                    UoWService.InitializeUoW(uowKey);
                }
                return UnitOfWork.Current; 
            }
        }

        public IUoWSession AsSession
        {
            get
            {
                if (UnitOfWork.Current == null)
                    UoWService.InitializeUoW(new Guid(HttpContext.Current.Request[LONG_CONVERSATION_KEY]));
                return HttpContext.Current.Items[UNIT_OF_WORK] as IUoWSession;
            }
        }

        public void ReplaceCurrentUnitOfWork(IUnitOfWork unitOfWork)
        {
            UoWService.ReplaceCurrentUnitOfWork(unitOfWork);
        }
    }
}